﻿using SqlSugar;

namespace MES.Server.Utility.InitDatabaseExt
{
    public static class InitSqlSugarExt
    {
        /// <summary>
        /// 初始化SqlSugar
        /// </summary>
        /// <param name="builder"></param>
        public static void InitSqlSugar(this WebApplicationBuilder builder)
        {
            CustomConnectionConfig customConnectionConfig = new CustomConnectionConfig();
            builder.Configuration.Bind("ConnectionStrings", customConnectionConfig);

            //注册SqlSugar的服务
            builder.Services.AddScoped<ISqlSugarClient>(s =>
            {
                ConnectionConfig connection = new ConnectionConfig()
                {
                    ConnectionString = customConnectionConfig.ConnectionString,
                    DbType = DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute,
                    SlaveConnectionConfigs = customConnectionConfig.SlaveConnectionConfigs.Select(c => new SlaveConnectionConfig() { ConnectionString = c.ConnectionString, HitRate = c.CustomHitRate }).ToList()
                };
                SqlSugarClient client = new SqlSugarClient(connection);


                //全局处理之后，后续只要是查询这些数据，自动多一个过滤条件
                //client.QueryFilter.AddTableFilter<Sys_Menu>(it => it.Status != (int)StatusEnum.Deleted);
                //client.QueryFilter.AddTableFilter<Sys_Role>(it => it.Status != (int)StatusEnum.Deleted);
                //client.QueryFilter.AddTableFilter<Sys_RoleMenuMap>(it => it.Status != (int)StatusEnum.Deleted);
                //client.QueryFilter.AddTableFilter<Sys_User>(it => it.Status != (int)StatusEnum.Deleted);
                //client.QueryFilter.AddTableFilter<Sys_UserRoleMap>(it => it.Status != (int)StatusEnum.Deleted);


                return client;
            });



        }
    }
}
